#include "WebEngineView.h"
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))

#include <QPaintEvent>
#include <QApplication>

WebEngineView::WebEngineView(QWidget *parent)
	: QWebEngineView(parent)
{
	this->setAttribute(Qt::WA_AcceptTouchEvents);
}

QWebEngineView * WebEngineView::createWindow(QWebEnginePage::WebWindowType type)
{
	if (type == QWebEnginePage::WebBrowserTab)
	{
		return this;
	}
	return QWebEngineView::createWindow(type);
}

bool WebEngineView::event(QEvent * ev)
{
	if (ev->type() == QEvent::ChildAdded) {
		QChildEvent *child_ev = static_cast<QChildEvent*>(ev);

		// there is also QObject child that should be ignored here;
		// use only QOpenGLWidget child
		QOpenGLWidget *w = qobject_cast<QOpenGLWidget*>(child_ev->child());
		if (w)
		{
			child_ = w;
			w->installEventFilter(this);
		}
	}
	return QWebEngineView::event(ev);
}

bool WebEngineView::eventFilter(QObject *obj, QEvent *ev)
{
	// emit delegatePaint on paint event of the last added QOpenGLWidget child
	if (obj == child_ && ev->type() == QEvent::Paint)
	{
		QPaintEvent *pe = dynamic_cast<QPaintEvent*>(ev);
		Q_UNUSED(pe)
		// do something with paint event
		// ...
		// or just emit signal to notify other objects
		//emit delegatePaint(pe);
	}
	else if (obj == child_ &&
		(ev->type() == QEvent::MouseButtonDblClick
			|| ev->type() == QEvent::MouseButtonPress
			|| ev->type() == QEvent::MouseButtonRelease
			|| ev->type() == QEvent::MouseMove
			|| ev->type() == QEvent::ContextMenu))
	{
		// QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(ev);
		QApplication::instance()->sendEvent(this, ev);
	}
	else if (!m_bIsArrowTool)
	{
		if (obj == child_ && ev->type() == QEvent::TouchBegin)
		{
			QTouchEvent *touchEvent = static_cast<QTouchEvent *>(ev);
			QMouseEvent *mouseEvent = new QMouseEvent(QEvent::MouseButtonPress,
				touchEvent->touchPoints().first().pos(),
				Qt::LeftButton,
				Qt::LeftButton,
				Qt::NoModifier);
			emit EventTransit(mouseEvent);
			return true;
		}
		else if (obj == child_ && ev->type() == QEvent::TouchUpdate)
		{
			QTouchEvent *touchEvent = static_cast<QTouchEvent *>(ev);
			QMouseEvent *mouseEvent = new QMouseEvent(QEvent::MouseMove,
				touchEvent->touchPoints().first().pos(),
				Qt::LeftButton,
				Qt::NoButton,
				Qt::NoModifier);
			emit EventTransit(mouseEvent);
			return true;
		}
		else if (obj == child_ && ev->type() == QEvent::TouchEnd)
		{
			QTouchEvent *touchEvent = static_cast<QTouchEvent *>(ev);
			QMouseEvent *mouseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
				touchEvent->touchPoints().first().pos(),
				Qt::LeftButton,
				Qt::LeftButton,
				Qt::NoModifier);
			emit EventTransit(mouseEvent);
			return true;
		}
	}
	return QWebEngineView::eventFilter(obj, ev);
}
#endif